package com.hfut.wxy.common.utils;

import com.hfut.wxy.common.exception.WxyException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtUtil {
    private static final String SIGN_KEY ="WxyTokenSecret";  //密钥盐


    public static String generateToken(Integer userId,String session_key){
        String token = null;
        try {
//            Date expiresAt = new Date(System.currentTimeMillis()+60*1000);
            token = Jwts.builder()
                    .claim("userId",userId)
                    .claim("session_key",session_key)
                    .setSubject(userId+"")
                    .signWith(SignatureAlgorithm.HS512, SIGN_KEY)
//                    .setIssuedAt(new Date())
//                    .setExpiration(expiresAt)
//                    .setNotBefore(new Date())
                    .compact();
        } catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }

    public static Claims validateToken(String token){
        try {
            return Jwts.parser()
                    .setSigningKey(SIGN_KEY)
                    .parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException eje) {
            throw WxyException.of("4002");
        } catch (Exception e){
            throw WxyException.of("4001");
        }
    }

}
